import React, { useEffect, useState } from 'react';
import { Button, Input, Select, Spin, Typography, Space, Divider, Card, Empty, Tag, List, Avatar } from 'antd';
import { SendOutlined, QuestionCircleOutlined, BookOutlined, FileTextOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../store';
import { fetchKnowledgeBases } from '../store/slices/knowledgeBase';
import { askQuestion } from '../store/slices/qa';
import PageHeader from '../components/common/PageHeader';
import { QAHistory, Source } from '../types/qa';

const { TextArea } = Input;
const { Title, Paragraph, Text } = Typography;
const { Option } = Select;

const QAPage: React.FC = () => {
  const dispatch = useDispatch();
  const { knowledgeBases } = useSelector((state: RootState) => state.knowledgeBase);
  const { currentQA, loading } = useSelector((state: RootState) => state.qa);

  const [question, setQuestion] = useState('');
  const [selectedKnowledgeBaseId, setSelectedKnowledgeBaseId] = useState<number | null>(null);
  const [history, setHistory] = useState<QAHistory[]>([]);

  useEffect(() => {
    dispatch(fetchKnowledgeBases() as any);
  }, [dispatch]);

  useEffect(() => {
    if (currentQA && !history.find(item => item.id === currentQA.id)) {
      setHistory([currentQA, ...history]);
      setQuestion('');
    }
  }, [currentQA, history]);

  const handleSend = () => {
    if (!question.trim() || !selectedKnowledgeBaseId) return;

    dispatch(askQuestion({
      question: question.trim(),
      knowledgeBaseId: selectedKnowledgeBaseId,
      topK: 3
    }) as any);
  };

  const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  // 渲染资源引用
  const renderSources = (sources: Source[]) => {
    return (
      <List
        size="small"
        header={<div>参考资料</div>}
        bordered
        dataSource={sources}
        renderItem={(source) => (
          <List.Item>
            <List.Item.Meta
              avatar={<Avatar icon={<FileTextOutlined />} style={{ backgroundColor: '#1890ff' }} />}
              title={
                <Space>
                  <Text strong>{source.documentName}</Text>
                  <Tag color="blue">相关度: {Math.round(source.similarity * 100)}%</Tag>
                  {source.page && <Tag color="green">页码: {source.page}</Tag>}
                </Space>
              }
              description={<div style={{ maxHeight: 100, overflow: 'auto' }}>{source.content}</div>}
            />
          </List.Item>
        )}
      />
    );
  };

  return (
    <div style={{ height: 'calc(100vh - 160px)', display: 'flex', flexDirection: 'column' }}>
      <PageHeader 
        title="智能问答" 
        breadcrumbs={[
          { title: '首页', path: '/' },
          { title: '智能问答' },
        ]}
      />

      <div style={{ display: 'flex', height: 'calc(100% - 48px)' }}>
        {/* 问答历史 */}
        <div style={{ 
          width: '70%', 
          padding: '16px', 
          overflowY: 'auto', 
          borderRight: '1px solid #f0f0f0',
          display: 'flex',
          flexDirection: 'column'
        }}>
          {history.length > 0 ? (
            <div className="qa-history">
              {history.map((qa) => (
                <div key={qa.id} style={{ marginBottom: 24 }}>
                  <div className="question" style={{ display: 'flex', marginBottom: 8 }}>
                    <Avatar 
                      style={{ backgroundColor: '#1890ff', marginRight: 12 }}
                      icon={<QuestionCircleOutlined />}
                    />
                    <div style={{ flexGrow: 1 }}>
                      <Text strong>{qa.question}</Text>
                    </div>
                  </div>
                  <div className="answer" style={{ marginLeft: 36, marginBottom: 8 }}>
                    <Paragraph>{qa.answer}</Paragraph>
                  </div>
                  {qa.sources?.length > 0 && (
                    <div style={{ marginLeft: 36 }}>
                      {renderSources(qa.sources)}
                    </div>
                  )}
                  <Divider />
                </div>
              ))}
            </div>
          ) : (
            <Empty 
              description="暂无对话历史，请开始提问"
              style={{ marginTop: 'auto', marginBottom: 'auto' }}
            />
          )}

          {/* 输入区域 */}
          <div style={{ marginTop: 'auto', position: 'sticky', bottom: 0, background: '#fff' }}>
            <div style={{ display: 'flex', alignItems: 'flex-end' }}>
              <TextArea 
                placeholder="请输入您的问题..." 
                value={question}
                onChange={(e) => setQuestion(e.target.value)}
                onKeyPress={handleKeyPress}
                autoSize={{ minRows: 1, maxRows: 6 }}
                style={{ flexGrow: 1, marginRight: 16, resize: 'none' }}
                disabled={loading || !selectedKnowledgeBaseId}
              />
              <Button 
                type="primary" 
                icon={<SendOutlined />} 
                onClick={handleSend}
                loading={loading}
                disabled={!question.trim() || !selectedKnowledgeBaseId}
              >
                发送
              </Button>
            </div>
            <div style={{ marginTop: 8 }}>
              <Select
                placeholder="请选择知识库"
                style={{ width: 200 }}
                value={selectedKnowledgeBaseId}
                onChange={(value) => setSelectedKnowledgeBaseId(value)}
              >
                {knowledgeBases.map(kb => (
                  <Option key={kb.id} value={kb.id}>
                    <Space>
                      <BookOutlined />
                      {kb.name}
                    </Space>
                  </Option>
                ))}
              </Select>
            </div>
          </div>
        </div>

        {/* 右侧信息 */}
        <div style={{ width: '30%', padding: '16px', overflowY: 'auto' }}>
          <Card title="使用说明" style={{ marginBottom: 16 }}>
            <Paragraph>
              1. 选择一个知识库
            </Paragraph>
            <Paragraph>
              2. 在输入框中输入您的问题
            </Paragraph>
            <Paragraph>
              3. 点击发送按钮或按Enter键提交问题
            </Paragraph>
            <Paragraph>
              4. 系统将基于选择的知识库内容回答您的问题
            </Paragraph>
          </Card>

          <Card title="知识库信息">
            {selectedKnowledgeBaseId ? (
              <div>
                {knowledgeBases
                  .filter(kb => kb.id === selectedKnowledgeBaseId)
                  .map(kb => (
                    <div key={kb.id}>
                      <Title level={5}>{kb.name}</Title>
                      <Paragraph>{kb.description}</Paragraph>
                      <div>
                        <Text type="secondary">文档数量: {kb.documentCount}</Text>
                      </div>
                      {kb.tags && kb.tags.length > 0 && (
                        <div style={{ marginTop: 8 }}>
                          {kb.tags.map(tag => (
                            <Tag key={tag}>{tag}</Tag>
                          ))}
                        </div>
                      )}
                    </div>
                  ))
                }
              </div>
            ) : (
              <Empty description="请选择一个知识库" />
            )}
          </Card>
        </div>
      </div>
    </div>
  );
};

export default QAPage;